import pymysql
import traceback
class DB:
    def __init__(self,user,password,database,host):
        self.user = user
        self.password = password
        self.database = database
        self.host = host
    def connect(self):
        # 创建数据库对象
        self.db = pymysql.connect(user = self.user,password=self.password,database=self.database
                        ,host=self.host,cursorclass=pymysql.cursors.DictCursor)
        # 创建游标
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def searchAll(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()
    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            traceback.print_exc()
        finally:
            self.close()
    def insert(self,sql):
        self.__edit(sql)
    def delete(self,sql):
        self.__edit(sql)
    def update(self,sql):
        self.__edit(sql)
"""
if __name__ == '__main__':
    # 创建对象
    d1 = DB('root','1965331442Xby@','crmeb','47.99.66.20')
    # 调用查询方法
    result = d1.searchAll('select * from eb_user_group')
    for i in result:
        print(i)
        if i['group_name'] =='曾晶':
            print(i['id'])
"""
if __name__ == '__main__':
    name = '曾晶'
    d1 = DB('root', '1965331442Xby@', 'crmeb', '47.99.66.20')
    result = d1.searchAll(f'select * from eb_user_group where group_name="{name}"')
    print(result)
    id = result[0]['id']
    print(id)

